package com.jack.payment.service.basic;


import com.jack.payment.dao.attach.AttachDao;
import com.jack.payment.entity.filter.RestFilter;
import com.jack.payment.entity.generate.attach.AttachModel;
import com.jack.payment.util.common.DownloadUtil;
import com.jack.payment.util.common.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletableFuture;


@Service
public class AttachServiceImpl {
    private Logger log = LoggerFactory.getLogger(this.getClass());


    @Autowired
    private AttachDao attachDao;
    @Autowired
    private DownloadUtil downloadUtil;

    public CompletableFuture<String> downloadAttach(String filePath, String url, String id) {
        if (!StringUtil.isValidURL(url)) {
            log.error("{} 此url 地址不是正确", url);
            return CompletableFuture.failedFuture(new IllegalArgumentException("无效的URL"));
        }
        String[] urlList = url.split("/");
        String suffixPath = urlList[urlList.length - 1];
        String[] fileTypeList = suffixPath.split("\\.");
        if (fileTypeList.length == 0) {
            log.error("无法从URL {} 中提取文件扩展名, ID: {}", url, id);
            return CompletableFuture.failedFuture(new IllegalArgumentException("无法提取文件扩展名"));
        }
        String saveFolds = filePath + id + "\\";
        String saveFile = saveFolds + id + "." + fileTypeList[fileTypeList.length - 1];
        return downloadUtil.downloadData(saveFile, saveFolds, url, id);
    }

    public void updateAttach(String tableName, String savePath, Integer page) {
        RestFilter.AttachFilter filter = new RestFilter.AttachFilter();
        filter.setEnable(0);
        filter.setCount(40);
        filter.setPage(page * 40);
        filter.setTable(tableName);
        List<AttachModel> attachList = attachDao.filterAttachRecordList(filter);
        List<CompletableFuture> futureList = new ArrayList<>();
        for (AttachModel attach : attachList) {
            futureList.add(downloadAttach(savePath, attach.getImg(), attach.getId()));
            futureList.add(downloadAttach(savePath, attach.getUrl(), attach.getId()));
        }
        CompletableFuture<Void> allDoneFuture = CompletableFuture.allOf(futureList.toArray(new CompletableFuture[0]));

        allDoneFuture.thenAccept(v -> {
            for (CompletableFuture<String> future : futureList) {
                // 这里不能直接获取结果，因为future可能已经完成，也可能有异常
                // 你可以使用future.join()来获取结果，但这会抛出异常
                // 更好的方法是使用future.handle(...)来处理每个future的结果和异常
                future.handle((result, throwable) -> {
                    if (throwable != null) {
                        // 处理异常
                        log.error("下载失败", throwable);
                    } else {
                        // 处理正常结果
                        log.info("下载成功，结果: {}", result);
                    }
                    return null; // handle方法需要返回Void或与future相同的结果类型
                });
            }
        });
        allDoneFuture.join();
    }
}
